package aliyun

import (
	"fmt"

	"gitee.com/ldysdy999/file-transfer-station/cloud-station/pro/store"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-playground/validator/v10"
)

var (
	val = validator.New()
)

type impl struct {
	AK       string `validate:"required"`
	SK       string `validate:"required"`
	EndPoint string `validate:"required"`

	Listener oss.ProgressListener //进度条函数所需要的接口
}

func NewAliYunOSSUploader(ak, sk, endpoint string) (store.OSSUpload, error) {
	loader := &impl{
		AK:       ak,
		SK:       sk,
		EndPoint: endpoint,
		Listener: NewAliOssProgressListener(), //初始化进度条接口的实例
	}
	if err := loader.Validate(); err != nil {
		return nil, fmt.Errorf("validate failed ,used by %s", err)
	}
	return loader, nil
}

func (i *impl) Validate() error {
	return val.Struct(i)
}

func (i *impl) Upload(bucketname, objectname, filename string) (fileURL string, err error) {
	client, err := oss.New(i.EndPoint, i.AK, i.SK)
	if err != nil {
		err = fmt.Errorf("New oss object failed")
		return
	}
	bucket, err := client.Bucket(bucketname)
	if err != nil {
		err = fmt.Errorf("find bucket is failed")
		return
	}

	progressoption := oss.Progress(i.Listener) //生成进度条option，传给PutObjectFromFile()
	err = bucket.PutObjectFromFile(objectname, filename, progressoption)
	if err != nil {
		err = fmt.Errorf("upload file %s is failed,maybe file is not exist\n", filename)
		return
	}

	//获取上传文件的链接
	return bucket.SignURL(objectname, oss.HTTPGet, 60*60*24*3) //最后传入的是设置链接有效时间
}
